package com.cap.dreamcircle.View;

import android.app.Dialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cap.dreamcircle.App.App;
import com.cap.dreamcircle.Base.BaseActivity;
import com.cap.dreamcircle.Consts.Constants;
import com.cap.dreamcircle.Model.Bean.BaseBean;
import com.cap.dreamcircle.Model.Bean.WechatAccessEntity;
import com.cap.dreamcircle.Model.Bean.WechatUserInfoEntity;
import com.cap.dreamcircle.Model.IExternalModel;
import com.cap.dreamcircle.Model.IUserModel;
import com.cap.dreamcircle.Model.Impl.ExternalModelImpl;
import com.cap.dreamcircle.Model.Impl.UserModelImpl;
import com.cap.dreamcircle.R;
import com.cap.dreamcircle.Utils.CommonSubscriber;
import com.cap.dreamcircle.Utils.DisplayUtil;
import com.cap.dreamcircle.Utils.RetrofitUploadFileParameterBuilder;
import com.cap.dreamcircle.Utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.RequestBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by liucxu on 2018/3/16.
 */

public class ChangeWechatActivity extends BaseActivity {

    @BindView(R.id.imv_back)
    ImageView imv_back;
    @BindView(R.id.layout_change_wechat)
    RelativeLayout layout_change_wechat;
    @BindView(R.id.tv_bind_wechat)
    TextView tv_bind_wechat;
    @BindView(R.id.tv_change_wechat)
    TextView tv_change_wechat;

    private TextView tv_cancel;
    private TextView tv_bind;

    private IExternalModel externalModel;
    private IUserModel userModel;
    private View dialogView;
    private Dialog notice_bind_dialog;

    private String wehcatNickname;
    private String preWXUnionId = "";

    private String wechatHeadImg = "";
    private String wechatNickName = "";
    private int wechatSex = -2;
    private String unionId = "";
    private File avasterFile;

    private IWXAPI api;

    @Override
    public int getLayoutId() {
        return R.layout.activity_change_wechat;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, Constants.WEIXIN_APPID, false);
        api.registerApp(Constants.WEIXIN_APPID);
        externalModel = new ExternalModelImpl();
        userModel = new UserModelImpl();
        wehcatNickname = getIntent().getStringExtra("key_wechat_nick_name");
        if(!TextUtils.isEmpty(getIntent().getStringExtra("key_UnionId"))){
            preWXUnionId=getIntent().getStringExtra("key_UnionId");
        }
        if (TextUtils.isEmpty(wehcatNickname)) {
            tv_change_wechat.setText("绑定");
        } else {
            tv_bind_wechat.setText(wehcatNickname);
            tv_change_wechat.setText("更换");
        }
        dialogView = View.inflate(ChangeWechatActivity.this, R.layout.dialog_bind_notify, null);
        initDialoigViews();
        initBindDialog();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(Constants.WECHAT_LOGIN_CODE_BIND)) {
            doRequestWechatInfo();
        }
    }

    private void initDialoigViews() {
        tv_cancel = (TextView) dialogView.findViewById(R.id.tv_cancel);
        tv_bind = (TextView) dialogView.findViewById(R.id.tv_bind);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notice_bind_dialog.dismiss();
            }
        });
        tv_bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBindWechat();
            }
        });
    }

    private void initBindDialog() {
        notice_bind_dialog = new Dialog(this, R.style.Theme_Light_Dialog);
        //获得dialog的window窗口
        Window window = notice_bind_dialog.getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.CENTER);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        android.view.WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = DisplayUtil.GetDisplayWidth() - DisplayUtil.dip2px(ChangeWechatActivity.this, 40);
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        notice_bind_dialog.setCancelable(false);
        notice_bind_dialog.setContentView(dialogView);
    }

    private void doRequestWechatInfo() {
        String request_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.WEIXIN_APPID + "&secret=" + Constants.WEIXIN_APPSECRET + "&code=" + Constants.WECHAT_LOGIN_CODE_BIND + "&grant_type=authorization_code";
        externalModel.getExternalRequest(request_url).flatMap(new Func1<JsonObject, Observable<WechatAccessEntity>>() {
            @Override
            public Observable<WechatAccessEntity> call(JsonObject jsonObject) {
                String json_string = jsonObject.toString();
                WechatAccessEntity access = (new Gson()).fromJson(json_string, WechatAccessEntity.class);
                return Observable.just(access);
            }
        }).flatMap(new Func1<WechatAccessEntity, Observable<JsonObject>>() {
            @Override
            public Observable<JsonObject> call(WechatAccessEntity wechatAccessEntity) {
                String request_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + wechatAccessEntity.getAccess_token() + "&openid=" + wechatAccessEntity.getOpenid();
                return externalModel.getExternalRequest(request_info_url);
            }
        }).flatMap(new Func1<JsonObject, Observable<WechatUserInfoEntity>>() {
            @Override
            public Observable<WechatUserInfoEntity> call(JsonObject jsonObject) {
                Constants.WECHAT_LOGIN_CODE_BIND="";
                String json_string = jsonObject.toString();
                WechatUserInfoEntity info = (new Gson()).fromJson(json_string, WechatUserInfoEntity.class);
                wechatHeadImg = info.getHeadimgurl();
                wechatNickName = info.getNickname();
                wechatSex = info.getSex();
                unionId = info.getUnionid();
                return Observable.just(info);
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<WechatUserInfoEntity>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(WechatUserInfoEntity wechatUserInfoEntity) {
                if (wechatUserInfoEntity.getUnionid().equals(preWXUnionId)) {
                    ToastUtils.showShortToast(ChangeWechatActivity.this, "您已经绑定这个微信账号，不需要重复绑定了.");
                } else {
                    testBindWechat();
                }
            }
        });
    }

    private void testBindWechat() {
        userModel.TestBindWechat(unionId).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                doBindWechat();
            }

            @Override
            public void onFailure(BaseBean response) {
                if(response.getCode()==1){
                    notice_bind_dialog.show();
                }
                else{
                    ToastUtils.showShortToast(ChangeWechatActivity.this,response.getDesc());
                }
            }
        });
    }

    private void doBindWechat() {
        RetrofitUploadFileParameterBuilder.newBuilder().cleanParams();
        Map<String, RequestBody> params = RetrofitUploadFileParameterBuilder.newBuilder()
                .addParameter("wxUnionId", unionId)
                .addParameter("wxUserName", wechatNickName)
                .addParameter("task","bdWx")
                .bulider();
        userModel.DoBindWechat(params).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response) {
                hideProgress();
                notice_bind_dialog.dismiss();
                ToastUtils.showShortToast(ChangeWechatActivity.this, "已经成功绑定");
                App.GetInstance().finishActivity(ChangeWechatActivity.this);
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                notice_bind_dialog.dismiss();
                ToastUtils.showShortToast(ChangeWechatActivity.this, response.getDesc());
            }
        });
    }

    @Override
    public void setupData() {

    }

    @OnClick({R.id.imv_back, R.id.layout_change_wechat})
    void doClicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.imv_back:
                App.GetInstance().finishActivity(ChangeWechatActivity.this);
                break;
            case R.id.layout_change_wechat:
                wechatLoginin();
                break;
        }
    }

    private void wechatLoginin() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_bind_state";
        api.sendReq(req);
    }
}
